package goplatform

import (
	"errors"
	"fmt"
	"log"
	"reflect"
)

func init() {
	ff, _ := GetFieldFactory()

	var fs = FieldInt{
		Name:     "int",
		Elements: FieldIntElement{Size: 5}}
	if err := ff.RegisterFieldType(&fs); err != nil {
		log.Println("FieldInt RegisterFieldType Fail")
	} else {
		log.Println("FieldInt RegisterFieldType Success")
	}
}

type FieldIntElement struct {
	Size     int  `orm:"int(8)" json:"size"`
	Unsigned bool `orm:"unsigned"`
}

type FieldInt struct {
	Name     string
	Elements FieldIntElement
	Errs     []error
}

func (f *FieldInt) CodeOrmStates() []string {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("\n-Recovered!-----------\nRecovered in CodeOrmStates", r)
			f.Errs = append(f.Errs, errors.New("FieldString CodeOrmStates recover! "))
		}
	}()
	//fmt.Printf("FieldString=>%+v\n", f)

	t := reflect.TypeOf(&f.Elements).Elem()
	var ormElementMap []string
	var (
		oSize     = t.Field(0).Tag.Get(fieldFactory.OrmTagName)
		oUnsigned = t.Field(1).Tag.Get(fieldFactory.OrmTagName)
	)
	if f.Elements.Size != 0 {
		oSize = "size:" + fmt.Sprintf("%d", f.Elements.Size)
		ormElementMap = append(ormElementMap, oSize)
	}
	if f.Elements.Unsigned {
		oUnsigned = "unsigned"
		ormElementMap = append(ormElementMap, oUnsigned)
	}
	//return fmt.Sprintf("gorm:\"%s\"", strings.Join(ormElementMap, ";"))
	return ormElementMap
}

func (f *FieldInt) EventUpdate() string {
	return "!!!!!FieldInt.EventUpdate"
}

func (f *FieldInt) GetName() string {
	return f.Name
}
